package com.zxy.supplier_system.server.repository

import com.zxy.supplier_system.server.entity.DirectSaleClient
import com.zxy.supplier_system.server.entity.DirectSaleOrder
import com.zxy.supplier_system.server.entity.Employee
import com.zxy.supplier_system.server.entity.SystemService
import com.zxy.supplier_system.server.utils.SpecificationUtils
import com.zxy.supplier_system.server.utils.joinOnce
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Slice
import org.springframework.data.jpa.domain.Specification
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.JpaSpecificationExecutor
import java.time.LocalDate

interface DirectSaleOrderRepository : JpaRepository<DirectSaleOrder, Int>, JpaSpecificationExecutor<DirectSaleOrder> {

    fun findByIdAndClient_SystemService(id: Int, market_systemService: SystemService): DirectSaleOrder?

    fun findAllByClient_Id(market_id: Int, pageable: Pageable): Slice<DirectSaleOrder>

    object Specifications {

        fun createdByIn(employeeIds: List<Int>): Specification<DirectSaleOrder> {
            return SpecificationUtils.`in`({ root ->
                root.joinOnce<DirectSaleOrder, Employee>("createdBy").get("id")
            }, employeeIds)
        }

        fun startDateGreaterThanOrEqualTo(startDate: LocalDate?): Specification<DirectSaleOrder> {
            return Specification { root, _, criteriaBuilder ->
                startDate?.let {
                    criteriaBuilder.greaterThanOrEqualTo(root.get("createdDateTime"), it)
                }
            }
        }

        fun endDateLessThanOrEqualTo(endDate: LocalDate?): Specification<DirectSaleOrder> {
            return Specification { root, _, criteriaBuilder ->
                endDate?.let {
                    criteriaBuilder.lessThanOrEqualTo(root.get("createdDateTime"), it)
                }
            }
        }

        fun clientIn(marketIds: List<Int>): Specification<DirectSaleOrder> {
            return SpecificationUtils.`in`({ root ->
                root.joinOnce<DirectSaleOrder, DirectSaleClient>("client").get("id")
            }, marketIds)
        }


    }


}

